package com.agent.crm.view;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import com.agent.crm.base.BaseActivity;
import com.pwp.activity.CalendarActivity;
import com.pwp.activity.CalendarWeekActivity;
import com.pwp.activity.ContactAttentionActivity;
import com.pwp.activity.ScheduleInfoView;
import com.pwp.activity.ScheduleView;
import com.pwp.constant.CalendarConstant;
import com.pwp.dao.ScheduleDAO;
import com.pwp.vo.ScheduleVO;

public class SearchActivity extends BaseActivity {

	private Drawable mIconSearchClear;
	private EditText text;
	private RadioButton btn_radio0;
	private RadioButton btn_radio1;
	private RadioButton btn_radio2;
	private RadioButton btn_radio3;
	
	
	private Button btn_contact;
	private Button btn_carlendar;
	private Button btn_search;
	private Button note_book;
	private Button btn_attention;
	
	private ScheduleDAO dao = null;
	private Button searchByTime;
	
	private Spinner s1;
	private EditText search_text_area;
	private EditText startTime;
	private EditText endTime;
	private int yearTemp;
	private int monthTemp;
	private int dayTemp;
	private int hourTemp;
	private int minuteTemp;
	ListView list;
	SimpleAdapter adapter;
	List<HashMap<String, String>> data;
	boolean time_picker_flag=false;
	
	public ArrayList<String> makeScheduleDate(String scheduleYear,String scheduleMonth,String scheduleDay,int position){
		String week = "";
		//得到这一天是星期几
        switch(position%7){
        case 0:
      	  week = "星期日";
      	  break;
        case 1:
      	  week = "星期一";
      	  break;
        case 2:
      	  week = "星期二";
      	  break;
        case 3:
      	  week = "星期三";
      	  break;
        case 4:
      	  week = "星期四";
      	  break;
        case 5:
      	  week = "星期五";
      	  break;
        case 6:
      	  week = "星期六";
      	  break;
        }
		 
        ArrayList<String> scheduleDate = new ArrayList<String>();
        scheduleDate.add(scheduleYear);
        scheduleDate.add(scheduleMonth);
        scheduleDate.add(scheduleDay);
        scheduleDate.add(week);
        //scheduleDate.add(scheduleLunarDay);
        return scheduleDate;
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
        switch (v.getId()) {
		case R.id.title_bt_setting:

			break;
		case R.id.search_by_time:
			searchResult();
			break;
		case R.id.schedule_and_carlendar:
			
            Intent intent = new Intent();
            SharedPreferences preferences =getSharedPreferences("scheduleStatusMode", Context.MODE_PRIVATE);
            String lunchMode =preferences.getString("CalendarDefaultLunchMode", "WeekCalendar");
            if (lunchMode.equalsIgnoreCase("DayCalendar")) {
            	Date date = new Date();
    	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
    	    	String currentDate = sdf.format(date);  //当期日期
    	    	String year_c = currentDate.split("-")[0];
    	    	String month_c = currentDate.split("-")[1];
    	    	String day_c = currentDate.split("-")[2];
    	    	Calendar car=Calendar.getInstance();
    	    	car.setTime(new Date());
    	    	ArrayList<String> scheduleDate = makeScheduleDate(year_c, month_c, day_c,car.get(Calendar.DAY_OF_WEEK)-1);
                intent.putStringArrayListExtra("scheduleDate", scheduleDate);
            	intent.setClass(this, ScheduleInfoView.class);
			}else if(lunchMode.equalsIgnoreCase("WeekCalendar")) {
				intent.setClass(this, CalendarWeekActivity.class);
			}else if(lunchMode.equalsIgnoreCase("MonthCalendar")) {
				intent.setClass(this, CalendarActivity.class);
			}
            startActivity(intent);
			break;
		case R.id.note_book:
            Intent noteIntent = new Intent();
            noteIntent.setClass(this, NoteBookActivity.class);
            startActivity(noteIntent);
            break;
		case R.id.attention_contact:
            Intent aatentionIntent = new Intent();
            aatentionIntent.setClass(this, ContactAttentionActivity.class);
            startActivity(aatentionIntent);
            break;
		case R.id.contact:
            Intent contactIntent = new Intent();
            contactIntent.setClass(this, MainActivity.class);
            startActivity(contactIntent);
            break;
		default:
			break;
		}
	}

	@Override
	protected int initLayout() {
		// TODO Auto-generated method stub
		return R.layout.search;
	}

	@Override
	protected View initCustomLayout() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void initViewCmp() {
		// TODO Auto-generated method stub
		
		btn_contact=(Button)findViewById(R.id.contact);
		btn_carlendar=(Button)findViewById(R.id.schedule_and_carlendar);
		btn_search=(Button)findViewById(R.id.search_contact_schedule);
		btn_search.setBackgroundResource(R.drawable.home_btn_bg_d);
		note_book=(Button)findViewById(R.id.note_book);
		btn_attention = (Button)findViewById(R.id.attention_contact);
		
	    dao = new ScheduleDAO(this);
	    data=new ArrayList<HashMap<String,String>>();
		mIconSearchClear = getResources().getDrawable(R.drawable.search);
		text = (EditText) findViewById(R.id.search_text_area);
		text.addTextChangedListener(tbxSearch_TextChanged);
		text.setOnTouchListener(txtSearch_OnTouch);
		text.setCompoundDrawablesWithIntrinsicBounds(null, null,
				mIconSearchClear, null);
		btn_radio0=(RadioButton)findViewById(R.id.radio0);
		btn_radio1=(RadioButton)findViewById(R.id.radio1);
		btn_radio2=(RadioButton)findViewById(R.id.radio2);
		btn_radio3=(RadioButton)findViewById(R.id.radio3);
		list =(ListView)findViewById(R.id.search_list);
		searchByTime=(Button) findViewById(R.id.search_by_time);
		
		search_text_area=(EditText)findViewById(R.id.search_text_area);
		startTime=(EditText)findViewById(R.id.start_time);
		endTime=(EditText)findViewById(R.id.end_time);
		
		showLayout(R.id.search_field_txt_layout);
		s1 = (Spinner) findViewById(R.id.schedule_status_spinner);
        ArrayAdapter<CharSequence> adapterSpanner = ArrayAdapter.createFromResource(
                this, R.array.schedule_status, android.R.layout.simple_spinner_item);
        adapterSpanner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        final Calendar c= Calendar.getInstance();
        c.setTime(new Date());
        yearTemp =c.get(Calendar.YEAR);
		monthTemp=c.get(Calendar.MONTH);
		dayTemp=c.get(Calendar.DAY_OF_MONTH);
		hourTemp= c.get(Calendar.HOUR_OF_DAY);
		minuteTemp=c.get(Calendar.MINUTE);
        startTime.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new DatePickerDialog(SearchActivity.this, new OnDateSetListener() {
					
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						// TODO Auto-generated method stub
						yearTemp =year;
						monthTemp=monthOfYear;
						dayTemp=dayOfMonth;
						TimePickerDialog time_dialog=new TimePickerDialog(SearchActivity.this, new OnTimeSetListener() {
							
							@Override
							public void onTimeSet(TimePicker view, int hourOfDay, int min) {
								time_picker_flag=false;
								hourTemp=hourOfDay;
								minuteTemp=min;
								startTime.setText(yearTemp+"-"+((monthTemp+1)<10?("0"+(monthTemp+1)):(monthTemp+1))+"-"+dayTemp+" "+hourTemp+":"+minuteTemp);
							}
						},hourTemp,minuteTemp, true);
						if(!time_picker_flag){
							time_dialog.show();
							time_picker_flag=true;
						}
					}
				},yearTemp,monthTemp,dayTemp).show();
			}
		});
        endTime.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new DatePickerDialog(SearchActivity.this, new OnDateSetListener() {
					
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {
						// TODO Auto-generated method stub
						yearTemp =year;
						monthTemp=monthOfYear;
						dayTemp=dayOfMonth;
						TimePickerDialog time_dialog=new TimePickerDialog(SearchActivity.this, new OnTimeSetListener() {
							
							@Override
							public void onTimeSet(TimePicker view, int hourOfDay, int min) {
								time_picker_flag=false;
								hourTemp=hourOfDay;
								minuteTemp=min;
								endTime.setText(yearTemp+"-"+((monthTemp+1)<10?("0"+(monthTemp+1)):(monthTemp+1))+"-"+dayTemp+" "+hourTemp+":"+minuteTemp);
							}
						},hourTemp,minuteTemp, true);
						if(!time_picker_flag){
							time_dialog.show();
							time_picker_flag=true;
						}
					}
				},yearTemp,monthTemp,dayTemp).show();
			}
		});
        s1.setAdapter(adapterSpanner);
        s1.setOnItemSelectedListener(
                new OnItemSelectedListener() {
                    public void onItemSelected(
                            AdapterView<?> parent, View view, int position, long id) {
                    	searchResult();
                    }

                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });
        adapter=new SimpleAdapter(this, data, R.layout.search_list_item, new String[]{"scheduleTitle","scheduleStatus","scheduleContent","scheduleDate","scheduleType"},new int[]{R.id.schedule_title,R.id.schedule_status,R.id.schedule_content,R.id.schedule_date,R.id.schedule_type});
        list.setAdapter(adapter);
	}
	
	private OnTouchListener txtSearch_OnTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_UP:
				int curX = (int) event.getX();
				if (curX > v.getWidth() - 68) {
					searchResult();
				}
				break;
			}
			return false;
		}
	};
	
	private TextWatcher tbxSearch_TextChanged = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			text.setCompoundDrawablesWithIntrinsicBounds(null, null,
					mIconSearchClear, null);
		}
	};

	@Override
	protected void initListener() {
		
		btn_contact.setOnClickListener(this);
		btn_carlendar.setOnClickListener(this);
		note_book.setOnClickListener(this);
		btn_attention.setOnClickListener(this);
		
		// TODO Auto-generated method stub
		btn_radio0.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d("TAG", "click");
				showLayout(R.id.search_field_txt_layout);
			}
		});
		btn_radio1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d("TAG", "click");
				showLayout(R.id.search_field_txt_layout);
			}
		});
		btn_radio2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d("TAG", "click");
				showLayout(R.id.search_field_cmobobox_layout);
			}
		});
		btn_radio3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d("TAG", "click");
				showLayout(R.id.search_time_field_layout);
			}
		});
		searchByTime.setOnClickListener(this);
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String scheduleID=data.get(arg2).get("scheduleID");
				Intent intentEdit = new Intent();
            	ScheduleVO scheduleVO = dao.getScheduleByID(Integer.valueOf(scheduleID));
            	intentEdit.putExtra("operateType", "edit");
            	intentEdit.putExtra("schedule", scheduleVO);
            	intentEdit.putExtra("from", "SearchActivity");
    			intentEdit.setClass(SearchActivity.this, ScheduleView.class);
		        startActivityForResult(intentEdit, 0);
			}
		});
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		searchResult();
	}

	private void showLayout(int id){
		if(id==R.id.search_field_txt_layout){
			findViewById(R.id.search_field_txt_layout).setVisibility(View.VISIBLE);
		}else{
			findViewById(R.id.search_field_txt_layout).setVisibility(View.GONE);
		}
		if(id==R.id.search_field_cmobobox_layout){
			findViewById(R.id.search_field_cmobobox_layout).setVisibility(View.VISIBLE);
		}else{
			findViewById(R.id.search_field_cmobobox_layout).setVisibility(View.GONE);
		}
		if(id==R.id.search_time_field_layout){
			findViewById(R.id.search_time_field_layout).setVisibility(View.VISIBLE);
		}else{
			findViewById(R.id.search_time_field_layout).setVisibility(View.GONE);
		}
	}

	private String convertStatusFlags(int flag){
		switch (flag) {
			case 0:
				return "未开始";
			case 1:
				return "进行中";
			case 2:
				return "已结束";
			default:
				return "";	
		}
	}
	
	private void searchResult(){
		Map <String,Object> map =new HashMap<String,Object>();
		if(btn_radio0.isChecked()){
			map.put("searchType", 0);
			map.put("title", search_text_area.getText().toString());
		}
		if(btn_radio1.isChecked()){
			map.put("searchType", 1);
			map.put("content", search_text_area.getText().toString());
		}
		if(btn_radio2.isChecked()){
			map.put("searchType", 2);
			map.put("status", s1.getSelectedItemPosition());
		}
		if(btn_radio3.isChecked()){
			map.put("searchType", 3);
			map.put("startTime", startTime.getText().toString());
			map.put("endTime", endTime.getText().toString());
		}
		List<ScheduleVO> scheduleList=dao.searchByCondition(map);
		data.clear();
		adapter.notifyDataSetChanged();
		if(null!=scheduleList){
			ScheduleVO scheduleVO = new ScheduleVO();
			for (int i = 0; i < scheduleList.size(); i++) {
				HashMap<String, String> resultMap=new HashMap<String, String>();
				scheduleVO=scheduleList.get(i);
				resultMap.put("scheduleID",String.valueOf(scheduleVO.getScheduleID()));
				resultMap.put("scheduleTitle",scheduleVO.getScheduleTitle());
				resultMap.put("scheduleDate", scheduleVO.getScheduleDate());
				resultMap.put("scheduleTypeID", CalendarConstant.sch_type[scheduleVO.getScheduleTypeID()]);
				resultMap.put("scheduleContent",scheduleVO.getScheduleContent());
				resultMap.put("scheduleType",CalendarConstant.sch_type[scheduleVO.getScheduleTypeID()]);
				resultMap.put("scheduleStatus",convertStatusFlags(Integer.valueOf(scheduleVO.getScheduleStatus())));
				data.add(resultMap);
			}
		}
		adapter.notifyDataSetChanged();
	}
	
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void initAsycnData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void changeDefaultSetting() {
		// TODO Auto-generated method stub

	}

}
